<template>
  <div class="streaming-table">
    <el-form ref="searchForm" :model="searchForm" :inline="true" label-width="100px">
      <el-form-item label="作业名称:">
        <el-input v-model="searchForm.name"></el-input>
      </el-form-item>
      <el-form-item label="作业类型:">
        <el-select v-model="searchForm.operator" placeholder="请选择" clearable>
          <el-option
            v-for="item in runTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableList" style="width: 100%">
      <el-table-column prop="task_id" label="TASK_ID" width="120"> </el-table-column>
      <el-table-column prop="name" label="作业名称"> </el-table-column>
      <el-table-column prop="operator" label="作业类型"  width="120"> </el-table-column>
      <el-table-column prop="execution_date" label="启动时间"  width="160">
        <template slot-scope="scope">
          {{ scope.row.execution_date | format }}
        </template>
      </el-table-column>
      <el-table-column prop="duration" label="耗时"> </el-table-column>
      <el-table-column prop="state" label="状态" width="100"> </el-table-column>
      <el-table-column prop="application_id" label="Yarn 任务ID">
        <template slot-scope="scope">
          <el-link
            v-if="scope.row.app_proxy_url"
            :href="scope.row.app_proxy_url"
            type="primary"
            target="_blank"
            >{{ scope.row.application_id }}</el-link
          >
          <span v-else>{{ scope.row.application_id }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="driver_proxy_url" label="Driver 日志">
        <template slot-scope="scope">
          <el-link
            v-if="scope.row.driver_proxy_url"
            :href="scope.row.driver_proxy_url"
            type="primary"
            target="_blank"
            >Driver 日志</el-link
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-popover
            v-if="scope.row.isStreaming"
            popper-class="managewarn"
            placement="top-start"
            trigger="hover"
            content="指标"
          >
            <el-button
              slot="reference"
              type="warning"
              icon="el-icon-s-data"
              size="mini"
              circle
              @click="index(scope.row)"
            ></el-button>
          </el-popover>
          <el-popover
            popper-class="managewarn"
            placement="top-start"
            trigger="hover"
            content="启动"
          >
            <el-button
              slot="reference"
              type="primary"
              icon="el-icon-video-play"
              size="mini"
              circle
              @click="start(scope.row)"
            ></el-button>
          </el-popover>
          <el-popover
            popper-class="managewarn"
            placement="top-start"
            trigger="hover"
            content="停止"
          >
            <el-button
              slot="reference"
              type="danger"
              icon="el-icon-video-pause"
              size="mini"
              circle
              @click="stop(scope.row)"
            ></el-button>
          </el-popover>
          <el-popover
            popper-class="managewarn"
            placement="top-start"
            trigger="hover"
            content="pod 日志"
          >
            <el-button
              slot="reference"
              type="success"
              icon="el-icon-download"
              size="mini"
              circle
               @click="downloadLog(scope.$index, scope.row)"
            ></el-button>
          </el-popover>
          
        </template>
      </el-table-column>
    </el-table>
    <div style="float: right; margin-top: 8px">
      <el-pagination
        :total="totalCount"
        :current-page="pageParams.page"
        layout="total, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
    <el-dialog
      title="指标监控"
      :visible.sync="showIndexChart"
      width="80%"
      :before-close="handleClose">
      <div class="index-search">
        <p>指标时间</p>
        <el-date-picker
          v-model="searchTime"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="left"
          @change="handleTime">
        </el-date-picker>
       </div>
      <IndexChart ref="index" :startTime="startTime" :endTime="endTime" :taskName="taskName" :taskId="taskId"/>
    </el-dialog>
    
  </div>
</template>

<script>
import IndexChart from './index-chart'
export default {
  name: "StreamingTable",
  data() {
    return {
      pageParams: {
        page: 1,
        pageSize: 10
      },
      totalCount: 0,
      searchForm: {
        name: "",
        operator: ""
      },
      statusList: [
        {
          id: "1",
          label: "failed",
          value: "failed"
        },
        {
          id: "2",
          label: "success",
          value: "success"
        },
        {
          id: "3",
          label: "running",
          value: "running"
        }
      ],
      runTypeList: [],
      tableList: [],
      // 指标监控
      taskName: '',
      taskId: '',
      showIndexChart: false,
      searchTime: [],
      startTime: '',
      endTime: '',
      pickerOptions: {}
    };
  },
  components:{
    IndexChart,
  },
  created() {
    this.$http.task.getTaskTypes().then(res => {
      this.runTypeList = res;
    });
    this.initData();
  },
  mounted() {
    this.startTime = new Date().getTime() - 3600 * 1000 * 24
    this.endTime = new Date().getTime()
    this.searchTime = [this.startTime, this.endTime]
    this.pickerOptions = {
      shortcuts: [{
        text: '最近一周',
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
          picker.$emit('pick', [start, end]);
        }
      }, {
        text: '最近一个月',
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
          picker.$emit('pick', [start, end]);
        }
      }, {
        text: '最近三个月',
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
          picker.$emit('pick', [start, end]);
        }
      }]
    }
  },
  methods: {
    index(row) {
      this.taskId = row.id
      this.taskName = row.name
      this.showIndexChart = true
      this.$refs.index && this.$refs.index.initData()
    },
    handleTime() {
      const [startTime, endTime] = this.searchTime
      this.startTime = startTime.getTime()
      this.endTime = endTime.getTime()
      console.log(startTime, this.startTime, endTime, this.endTime)
      this.$refs.index.initData()
    },
    downloadLog(index, row) {
      this.$http.task
        .downloadTaskLog({
          hostname: row.hostname,
          operator: row.operator,
          start: -1000
        })
        .then(res => {
          const blob = new Blob([res], { type: "application/octet-stream" });
          let dom = document.createElement("a");
          let url = window.URL.createObjectURL(blob);
          dom.href = url;
          dom.download = decodeURI(row.hostname + ".log");
          dom.style.display = "none";
          document.body.appendChild(dom);
          dom.click();
          dom.parentNode.removeChild(dom);
          window.URL.revokeObjectURL(url);
        });
    },
    search() {
      this.pageParams = {
        page: 1
      };
      this.initData();
    },
    start(row) {
      this.$http.task.runTask({ task_id: row.id }).then(res => {
        this.$message({
          message: "启动完成",
          type: "success"
        });
        this.initData();
      });
    },
    stop(row) {
      this.$http.task
        .stopTask({
          task_id: row.task_id,
          dag_id: row.dag_id,
          execution_date: row.execution_date
        })
        .then(res => {
          this.$message({
            message: "已停止",
            type: "success"
          });
          this.initData();
        });
    },
    handleCurrentChange(val) {
      this.pageParams.page = val;
      this.initData();
    },
    initData() {
      this.$http.streaming
        .getStreamingList({
          ...this.pageParams,
          ...this.searchForm,
          project_id: this.$route.query.project_id
        })
        .then(res => {
          this.tableList =
            res.items.length > 0
              ? res.items.map(item => {
                  var obj = {
                    id: item.id,
                    name: item.name,
                    operator: item.operator,
                    isStreaming: item.type == 1 ? true : false,
                    execution_date: "",
                    duration: "",
                    state: "",
                    dag_id: "",
                    task_id: ""
                  };
                  if (item.task_instance) {
                    obj.hostname=item.task_instance.hostname
                    obj.application_id=item.task_instance.application_id
                    obj.execution_date = item.task_instance.execution_date;
                    obj.duration = item.task_instance.duration;
                    obj.state = item.task_instance.state;
                    obj.dag_id = item.task_instance.dag_id;
                    obj.task_id = item.task_instance.task_id;
                    obj.app_proxy_url = item.task_instance.app_proxy_url;
                    obj.driver_proxy_url = item.task_instance.driver_proxy_url;
                  }
                  return obj;
                })
              : [];
          this.totalCount = res.total;
        });
    }
  }
};
</script>
<style lang="scss" scoped>
.index-search{
  margin: 0 30px;
  display: flex;
  align-items: center;
  p{
    font-size: 16px;
    margin-right: 10px;
  }
}
</style>
